package com.liang;

import com.alibaba.fastjson.JSONObject;
import com.sun.corba.se.impl.orbutil.CorbaResourceUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class TestTX {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.flushDB();
        //开启事务
        Transaction multi = jedis.multi();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "world");
        jsonObject.put("name", "liangwh");
        String jsonString = jsonObject.toJSONString();
        try {
            multi.set("user1", jsonString);
            multi.set("user2", jsonString);
//                int i = 1/0; //模拟代码有问题，事务失败
//      jedis.watch(jsonString);监听
            multi.exec();//正常情况，执行事务
        }catch (Exception e){
            multi.discard();//有异常，放弃事务
            e.printStackTrace();
        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();//关闭连接
        }
    }
}
